import { Injectable } from "@angular/core";
import { HttpService, HTTPMethods, APIPath } from "http-service";
import { PickerColumn, PickerController, PopoverController, AlertController } from "ionic-angular";
import { SecureStorageService } from "./secure-storage.services";
import { FileTransfer, FileTransferObject } from '@ionic-native/file-transfer';
import { Observable } from 'rxjs';
import { File } from '@ionic-native/file';
import { API } from "../models/api-path-extension";
import { Device } from "@ionic-native/device";
import { ReloadingController } from "../components/reloading/reloading-controller";
import { Platform } from "ionic-angular";
import { PhotoViewer } from "@ionic-native/photo-viewer";

// import { ReloadingController } from '../components/reloading/reloading-controller';
declare enum LocalFileSystem {
  PERSISTENT= 0,
  TEMPORARY= 1
}

declare let cordova: any;

declare let window: {
  requestFileSystem: any,
  resolveLocalFileSystemURL: any
};

@Injectable()
export class UtilsService {
  static loadingObject: Array<any> = [];
  fileTransfer: FileTransferObject ;
  imgSrc: string;
  token: string;

  constructor(
    public popover: PopoverController,
    public alertCtrl: AlertController,
    public pickerCtrl: PickerController,
    private storage: SecureStorageService,
    private device: Device,
    private transfer: FileTransfer,
    private file: File,
    private platform: Platform,
    private httpService: HttpService,
    private loadingCtrl: ReloadingController,
    private photoViewer: PhotoViewer
    // public loadingCtrl: ReloadingController
  ) {
      this.fileTransfer = this.transfer.create();
  }

  // popUp
  // tslint:disable-next-line:ban-types
  public popPicker(dateArr: Array<PickerColumn>, cssClass?: string, confirmHandler?: Function, cancelHandler?: Function) {
    let picker = this.pickerCtrl.create({
      buttons: [
        {
          text: '取消',
          role: 'cancel',
          handler: cancelHandler || (() => { console.log(); })
        },
        {
          text: '确认',
          handler: confirmHandler || (() => { console.log(); })
        }
      ],
      cssClass: 'ntrip-picker ' + cssClass,
      columns: dateArr
    });
    picker.present();
    return picker;
  }

  // sort
  public getSort(listArray: any, isSort: boolean, key: string) {
    listArray.sort(this.sortFunction(isSort, key));
    return listArray;
  }

  // 提示框
  tip(msg = '提示框', butText = '确定') {
    let alert = this.alertCtrl.create({
      message: `<div>${msg}</div>`,
      cssClass: "tip-alter",
      buttons: [
        {
          cssClass: "tip-button-alter",
          text: butText,
          handler: () => {
            console.log('Buy clicked');
          }
        }
      ]
    });
    alert.present();
  }

  public showLoading(content: {
    text?: string
  } = {
    text: "拼命加载中，请稍后..."
  }) {
    UtilsService.loadingObject.push(this.loadingCtrl.create({content: content.text}));
    let index = UtilsService.loadingObject.length - 1;
    UtilsService.loadingObject[index].present();
    return index;
    // TODO
  }

  public hiddenLoading(index: number = 0) {
    if (UtilsService.loadingObject.length <= 0 || UtilsService.loadingObject.length - 1 < index) {
      return ;
    }
    UtilsService.loadingObject[index].dismiss();
    UtilsService.loadingObject.shift();
  }

  public getCounter(date = null) {
    let counter = 1;
    let isOverTime = false;
    if (date) {
      let curTime = +new Date();
      counter = curTime - date;
      counter = 12 * 70 - counter;
      if (counter < 0) {
        isOverTime = true;
        counter = (-1) * counter;
      }
      counter = counter > 5999 ? 5999 : counter;
      counter = counter * 60 + 1;
    }
    return {
      isOverTime: isOverTime,
      counter: counter
    };
  }

  public productionCountdown(counter = 1) {
    return Observable.timer(0, 1000 * 60)
      .take(counter)
      .map(() => {
        --counter;
        if (counter === 0) {
          // TODO
        }
        return counter;
      });
  }

  getImage() {
      return this.httpService.downloadFile(
        new API().path({ path: "attachment", method: HTTPMethods.Get, param: "/1807311832217" }),
        this.file.dataDirectory + 'imageName.jpg',
        'imageName.jpg'
      );
  }

  public downByIdArray(attachmentIds: Array<string>) {
    let attachmentObservable: Array<any>;
    attachmentObservable = attachmentIds.map((attachmentId) => {
      return this.downImage(attachmentId);
    });
    return Observable.combineLatest(attachmentObservable)
      .map((downloadArray) => {
        return downloadArray;
      });
  }

  // 下载图片
  public downImage(id: string, token: string = "", fileSuffix = ".jpg", url = null) {
    // let attachmentUrl = new API().path({ path: "attachment"}).url + '/' + id;
    // let imgName = attachmentUrl.split('/');
    if (this.device.cordova) {
        return Observable.create((ob) => {
          Observable.fromPromise(this.file.checkFile(this.file.dataDirectory, id + fileSuffix))
            .subscribe((bool) => {
            if (bool) {
              let data = {
                nativeURL: this.file.dataDirectory + id + fileSuffix,
                id: id
              };
              if (this.platform.is("ios") && fileSuffix === ".jpg") {
                data["nativeURL"] = data["nativeURL"].replace("file://", "");
              }
              ob.next(data);
              ob.complete();
            } else {
              ob.next({
                nativeURL: ""
              });
              ob.complete();
            }
          }, (e) => {
              let param = {};
              if (!url) {
                url = new API().path({ path: "attachment", method: HTTPMethods.Get, param: "/" + id });
              } else {
                param = url["param"];
                url = url["url"];
              }
              this.httpService.downloadFile(
                url,
                this.file.dataDirectory + id + fileSuffix,
                id + fileSuffix,
                {},
               null ,
                null,
                param
              )
                .map((data) => {
                  data["id"] = id;
                  if (this.platform.is("ios") && fileSuffix === ".jpg") {
                    data["nativeURL"] = data["nativeURL"].replace("file://", "");
                  }
                  return data;
                })
                .catch((error) => {
                  return Observable.throw(error);
                })
                .subscribe((data) => {
                  ob.next(data);
                  ob.complete();
                }, (data) => {
                  if (!data["nativeURL"]) {
                    data["id"] = id;
                    data["nativeURL"] = "";
                  }
                  ob.next(data);
                  ob.complete();
                });
            });
        });
    } else {
      return Observable.create((subscriber) => {
        subscriber.next({
          id: id,
          nativeURL: "https://img.alicdn.com/bao/uploaded/TB1qimQIpXXXXXbXFXXSutbFXXX.jpg",
          toURL: () => {
            return "https://img.alicdn.com/bao/uploaded/TB1qimQIpXXXXXbXFXXSutbFXXX.jpg";
          }
        });
        subscriber.complete();
      });
    }
  }

  // 打开文件系统
  public getFillSystem(fileName, defineDir: string = 'wudangImgDir') {
    return Observable.create((subscriber) => {
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, (fs) => {
          fs.root.getDirectory(defineDir, {create: true}, (dirEntry) => {
            dirEntry.getFile(fileName, {create: true, exclusive: false},  (fileEntry) => {
              subscriber.next(fileEntry);
              subscriber.complete();
            });
        }, (e) => {
          console.log("文件系统加载失败！", e);
          subscriber.error(e);
        });
      });
    });
  }

  public writeFile(fileEntry, blob) {
  // 创建一个写入对象
    return Observable.create((subscriber) => {
      fileEntry.createWriter((fileWriter) => {

        // 文件写入成功
        fileWriter.onwriteend = () => {
          console.log("Successful file write...");
          if (blob.type === "image/png") {
            subscriber.next(fileEntry);
            subscriber.complete();
            // this.readBinaryFile(fileEntry);
          }
          console.log("Successful file write...");

        };

        // 文件写入失败
        fileWriter.onerror = (e) => {
          console.log("Failed file write: " + e.toString());
          subscriber.error(e);
        };
        // 写入文件
        fileWriter.write(blob);
      });
    });
  }

  readBinaryFile(fileEntry) {
    return Observable.create((subscriber) => {
      fileEntry.file((file) => {
        let reader = new FileReader();
        reader.onloadend = function() {
          console.log("Successful file write: " + this.result);
          subscriber.next(fileEntry);
          subscriber.complete();
        };
        reader.readAsArrayBuffer(file);
      }, () => {
        console.log("error");
      });
    });
  }

    // 下载文件
  public downFile(id: string, token: string) {
    let attachmentUrl = new API().path({ path: "attachment"}).url + '/' + id;
    let imgName = attachmentUrl.split('/');
    let url = attachmentUrl + '?access_token=' + token;
    return Observable.fromPromise(this.fileTransfer.download(url, this.file.dataDirectory + imgName[imgName.length - 1] + '.docx'));
  }

  public showBigPic(image) {
    this.showLoading();
    this.downImage(image.id).subscribe((path) => {
      this.hiddenLoading();
      if (path.nativeURL) {
        this.photoViewer.show(path.nativeURL);
      } else {
        this.photoViewer.show(image.path);
      }
    }, () => {
      this.hiddenLoading();
      this.photoViewer.show(image.path);
    });
  }

  private smallSort(key: string) {
    return (a, b) => a[key] - b[key];
  }

  private sortFunction(arc: boolean, key: string) {
    return arc ? this.largeSort(key) : this.smallSort(key);
  }

  private largeSort(key: string) {
    return (a, b) => b[key] - a[key];
  }

  // tslint:disable-next-line:member-ordering
  // public showTip(
  // showInfo: any = {resultFlag: true, message: '', successImg:  null, failedImg: null},
  // showConfig: any = {hiddenTimeOut: 500, autoClose: true, onDismiss: null}) {
  //     const resultPop = this.popover.create(MessageShowComponent, showInfo, {
  //         cssClass: 'message-page',
  //         enableBackdropDismiss: false
  //     });

  //     showConfig = showConfig || {};

  //     if (showConfig.onDismiss) {
  //         resultPop.onDidDismiss(showConfig.onDismiss);
  //     }

  //     resultPop.present();

  //     if (showConfig.autoClose === undefined || showConfig.autoClose === null) {
  //         showConfig.autoClose = true;
  //     }
  //     if (showConfig.autoClose) {
  //         setTimeout(() => {
  //             if (resultPop) {
  //                 resultPop.dismiss('', '', {animate: false});
  //             }
  //         }, showConfig.hiddenTimeOut || 500);
  //     }
  // }

}
